import React, {Component} from 'react';
import {Table, Checkbox, Radio, Space} from 'antd';

function AuthSelect(props) {
  const {value = {}, dataSourceOptionsKey, onChange, scopeModuleKey, scope} = props;

  const onActionCheck = (rowKey, checked, keys) => {
    let {actions = [], ...otherData} = (value[rowKey] || {});
    if (checked) {
      actions = [...actions, ...keys];
    } else {
      actions = actions.filter(item => !keys.includes(item))
    }
    const val = {
      ...value,
      [rowKey]: {
        ...otherData,
        actions: actions,
      }
    }
    onChange(val);
  }

  const onScopeChange = (rowKey, val) => {
    onChange({
      ...value,
      [rowKey]: {
        ...value[rowKey],
        scope: val
      }
    });
  }

  return <Table size="small" pagination={false} dataSource={scope[scopeModuleKey]} columns={[
    {dataIndex: 'name', title: '模块', width: 120},
    {
      dataIndex: 'actions', title: '功能权限', render: (text, row) => {
        const {actions = []} = (value[row.key] || {});
        const keys = text.map(item => item.key);
        const checked = keys.filter(key => actions?.includes(key));
        return <span>
        <div>
          <Checkbox indeterminate={checked.length < keys.length && checked.length > 0}
                    checked={checked.length === keys.length}
                    onChange={e => onActionCheck(row.key, e.target.checked, keys)}>全选</Checkbox>
        </div>
          <div>
            {text.map(item =>
              <Checkbox checked={actions?.includes(item.key)}
                        onChange={e => onActionCheck(row.key, e.target.checked, [item.key])}
                        key={item.key}>{item.name}</Checkbox>)}
          </div>
      </span>
      }
    },
    {
      dataIndex: 'dataAuth',
      title: '数据权限',
      width: 250,
      render: (text, row) =>
        <Radio.Group name={`key_${row.id}`}
                     value={value[row.key]?.scope}
                     onChange={(e) => onScopeChange(row.key, e.target.value)}>
          <Space direction="vertical">
            {scope[dataSourceOptionsKey].map(item => <Radio key={item.key} value={item.key}>{item.name}</Radio>)}
          </Space>
        </Radio.Group>
    },
  ]}/>
}

export default AuthSelect;
